package com.deep.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.deep.common.model.constant.ProductConstant;
import com.deep.product.dao.AttrAttrgroupRelationDao;
import com.deep.product.dao.AttrGroupDao;
import com.deep.product.dao.CategoryDao;
import com.deep.product.model.entity.AttrAttrgroupRelationEntity;
import com.deep.product.model.entity.AttrGroupEntity;
import com.deep.product.model.entity.CategoryEntity;
import com.deep.product.model.vo.AttrRespVO;
import com.deep.product.model.vo.AttrVO;
import com.deep.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deep.common.utils.PageUtils;
import com.deep.common.utils.Query;

import com.deep.product.dao.AttrDao;
import com.deep.product.model.entity.AttrEntity;
import com.deep.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttrVO(AttrVO attrVO) {
        // 保存基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);

        this.save(attrEntity);

        // 保存关联关系
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        // 获取保存的attrEntity.attrId
        relationEntity.setAttrId(attrDao.getMaxAttrId());
        relationEntity.setAttrGroupId(attrVO.getAttrGroupId());

        relationDao.insert(relationEntity);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities
                .stream()
                .map((attr) -> attr.getAttrId())
                .collect(Collectors.toList());

        // 根据这个属性查询到的id可能是空的
        if (attrIds.size() == 0) {
            return null;
        }
        return this.listByIds(attrIds);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        Long catalogId = attrGroupDao.selectById(attrgroupId).getCatelogId();
        if (attrgroupId == null) {
            throw new IllegalArgumentException("attrgroupId异常!");
        }

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id", catalogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        // 进行key过滤
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wrapper.like("attr_name", key).or().like("value_select", key);
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        // 查询包装器
        QueryWrapper<AttrEntity> queryWrapper =
                new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type)
                        ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                        : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        // 获取检索值
        String key = (String) params.get("key");

        if (StringUtils.hasLength(key)) {
            //attr_id  attr_name
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVO> respVos = records.stream().map((attrEntity) -> {
            AttrRespVO attrRespVO = new AttrRespVO();

            BeanUtils.copyProperties(attrEntity, attrRespVO);

            //1、设置分类和分组的名字
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity attrId =
                        relationDao.selectOne(
                                new QueryWrapper<AttrAttrgroupRelationEntity>()
                                        .eq("attr_id", attrEntity.getAttrId()));

                if (attrId != null && attrId.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());

            if (categoryEntity != null) {
                attrRespVO.setCatelogName(categoryEntity.getName());
            }
            return attrRespVO;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);

        return pageUtils;
    }

    @Cacheable(value = "attr", key = "'attrinfo:' + #root.args[0]")
    @Transactional
    @Override
    public AttrRespVO getAttrInfo(Long attrId) {
        AttrRespVO attrRespVO = new AttrRespVO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVO);
        // ①、setAttrGroupId     ②、setGroupName      ③、setCatalogPath    ④、setCatalogName

        // 获取属性类型    (属性类型[0-销售属性，1-基本属性，2-既是销售属性又是基本属性])
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 基本属性才进行修改
            // 获取"属性-属性分组对应实体"
            AttrAttrgroupRelationEntity attrgroupRelation =
                    relationDao.selectOne(
                            new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            // 从"属性-属性分组对应实体"中获取"最新"的属性分组id
            if (attrgroupRelation != null) {
                // "最新"的属性分组id
                Long lastAttrGroupId = attrgroupRelation.getAttrGroupId();
                // ①、setAttrGroupId
                attrRespVO.setAttrGroupId(lastAttrGroupId);
                // 利用"属性分组id"再从"属性分组实体"中获取"属性分组实体"
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(lastAttrGroupId);
                if (attrGroupEntity != null) {
                    // ②、setGroupName
                    attrRespVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //  设置分类信息
        Long catalogId = attrEntity.getCatelogId();
        Long[] catalogPath = categoryService.findCatalogPath(catalogId);
        // ③、setCatalogPath
        attrRespVO.setCatelogPath(catalogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catalogId);
        if (categoryEntity != null) {
            // ④、setCatalogName
            attrRespVO.setCatelogName(categoryEntity.getName());
        }
        return attrRespVO;
    }

    @Transactional  // 事务：下面的都操作成成功才算成功
    @Override
    public void updateAttrVO(AttrVO attrVO) {
        // 更新属性表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);

        this.updateById(attrEntity);

        // 为基本属性时进行关联表修改
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attrVO.getAttrGroupId());
            relationEntity.setAttrId(attrVO.getAttrId());

            Integer count = relationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrVO.getAttrId()));

            if (count > 0) {
                relationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrVO.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }
    }

    @Transactional
    @Override
    public void deleteDetail(Long[] attrIds) {
        Assert.notNull(attrIds, "属性id不能为空!");
        // ①、删除属性表
        this.removeByIds(Arrays.asList(attrIds));
        // ②、删除关联表
        relationDao.deleteByAttrIds(attrIds);
    }

}